package com.lingo.ffmpegdemo.file;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import jdk.internal.instrumentation.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * 文件批量重命名
 */
public class FileReName {
    private static  Log logger = LogFactory.get(FileReName.class);
    private static  String TAG = "关闭或者异常";
    public static void main(String[] args) {
        String path = "D:\\网盘下载\\12、 分布式协调服务器Zookeeper";
       doFile(path);

    }

    /**
     * 递归获取文件、复制文件、删除文件
     * @param path
     */
    public static  void doFile(String path){
        File file =new File(path);
        String[] list = file.list();
        for (String s : list) {
                String newPath = path+"\\"+s;
                File dFile = new File(path+"\\"+s);
                if (dFile.isDirectory()){
                    doFile(newPath);
                }else {
                    if (s.contains("论坛")) {
                        String replace = s.replace("【瑞客论坛 www.ruike1.com】", "");
                        replace = replace.replace("第一十二章第1节： ", "");
                        copyNio(path + "\\" + s, path + "\\" + replace);
                        dFile.delete();
                    }
                }
            }
        }

    /**
     * 文件复制
     * @param source
     * @param dest
     */
    public static void copyNio(String source, String dest) {
        FileChannel input = null;
        FileChannel output = null;

        try {
            //from
            input = new FileInputStream(new File(source)).getChannel();
            //to
            output = new FileOutputStream(new File(dest)).getChannel();
            output.transferFrom(input, 0, input.size());
        } catch (Exception e) {

           logger.info (TAG + "copyNio", "error occur while copy", e);
        } finally {
            safelyClose(TAG + "copyNio", input);
            safelyClose(TAG + "copyNio", output);
        }
    }

    /**
     * 关流
     * @param tag
     * @param fileChannel
     */
    public static void safelyClose(String tag,FileChannel fileChannel){
        logger.info (tag + "copyNio", "close fileChannel");
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
